import axios from "axios";

// 生产环境
// const WEB_URL = "http://27.150.175.210:8082/v1";
// const WEB_URL1 = "http://27.150.175.210:8082/v2";
// 测试环境
// const WEB_URL = "http://27.150.175.210:8910/v1";
// const WEB_URL1 = "http://27.150.175.210:8911/v2";
// 本地
// const WEB_URL = "http://localhost:8910/v1";
// const WEB_URL1 = "http://localhost:8911/v2";
const baseURL = JSON.parse(localStorage.getItem("config")).baseURL;
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("mvToken");
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.data.code === -1 && response.data.data === "未登录") {
      localStorage.removeItem("mvToken");
      setTimeout(() => {
        window.location.reload();
      }, 200);
    }
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token信息并跳转到登录页面
          localStorage.removeItem("mvToken");
          window.location.reload();
          break;
      }
    }
    return Promise.reject(error.response);
  }
);
const util = {
  // 请求封装
  post(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .post(baseURL.WEB_URL + url, params, {})
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 请求封装1
  post1(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .post(baseURL.WEB_URL1 + url, params, {})
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  get1(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .get(baseURL.WEB_URL1 + url)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
};
export default util;
